const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatTime2 = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return year + '年' + month + '月' + day + '日'
}
const formatTime3 = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  // return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  return year + '年' + month + '月' + day + '日 ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 生成指定长度的随机数
const randomNumber = (length) => {
  return Math.floor( Math.random() * ( Math.pow( 10 , length) ) + length * Math.pow( 10 , (length - 1) ) )
}

// 根据传入时间格式返回对应当前时间
const getCustomTime = (format) => {
  var date = new Date();

  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  var str = format + '';
  if( format.indexOf("yyyy") != -1 ){
    str = str.replace('yyyy' , year);
  }
  if(format.indexOf("MM") != -1){
    str = str.replace('MM' , month);
  }
  if(format.indexOf("dd") != -1){
    str = str.replace('dd' , day);
  }
  if(format.indexOf("hh") != -1){
    str = str.replace('hh' , hour);
  }
  if(format.indexOf("mm") != -1){
    str = str.replace('mm' , minute);
  }
  if(format.indexOf("ss") != -1){
    str = str.replace('ss' , second);
  }
  
  return str;
}

module.exports = {
  formatTime: formatTime,
  YMD: formatTime2,
  YMDHMS: formatTime3,
  randomNumber: randomNumber,
  getCustomTime: getCustomTime
}
